<template>
  <div class="customer-dashboard-container">
    <!-- 顶部欢迎区域 -->
    <WelcomeCard />
    
    <!-- 状态卡片区域 -->
    <StatCards :order-stats="orderStats" />
    
    <!-- 最近订单和收货地址 -->
    <div class="main-content">
      <RecentOrders :recent-orders="recentOrders" :loading="loading" />
      <FrequentAddresses :frequent-addresses="frequentAddresses" :loading="loading" />
    </div>
    
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { userApi } from '@/api/user'
import WelcomeCard from './components/WelcomeCard.vue'
import StatCards from './components/StatCards.vue'
import RecentOrders from './components/RecentOrders.vue'
import FrequentAddresses from './components/FrequentAddresses.vue'


const loading = ref(true)

// 订单统计数据
const orderStats = reactive({
  total: 0,
  pending: 0,
  processing: 0,
  completed: 0,
  deliverying: 0
})

// 最近订单数据（限制为3条）
const recentOrders = ref([])

// 常用地址数据
const frequentAddresses = ref([])

// 获取订单统计数据
const fetchOrderStats = async () => {
  try {
    const response = await userApi.getOrderStats()
    if (response.code === 200) {
      Object.assign(orderStats, response.data)
    } else {
      ElMessage.error(response.msg?.toString() || '获取订单统计失败')
    }
  } catch (error) {
    console.error('获取订单统计失败:', error)
    ElMessage.error('获取订单统计失败')
  }
}

// 获取最近订单数据（只获取3条）
const fetchRecentOrders = async () => {
  try {
    const response = await userApi.getDeliveryOrderCount(1, 3)
    if (response.code === 200) {
      recentOrders.value = response.data.list
    } else {
      ElMessage.error(response.msg?.toString() || '获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  }
}

// 获取常用地址数据
const fetchFrequentAddresses = async () => {
  try {
    const response = await userApi.getFrequentAddresses()
    console.log('常用地址响应:', response) // 调试日志
    if (response.code === 200) {
      // 根据您的数据格式，数据在 response.data 中
      frequentAddresses.value = response.data || []
      console.log('设置的地址数据:', frequentAddresses.value)
    } else {
      ElMessage.error(response.msg || '获取常用地址失败')
    }
  } catch (error) {
    console.error('获取常用地址失败:', error)
    ElMessage.error('获取常用地址失败')
  }
}

onMounted(async () => {
  try {
    await Promise.all([
      fetchOrderStats(),
      fetchRecentOrders(),
      fetchFrequentAddresses()
    ])
  } finally {
    loading.value = false
  }
})
</script>

<style scoped>
.customer-dashboard-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 统计卡片区域 */
.main-content {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
  gap: 20px;
  overflow: visible;
}

@media (max-width: 768px) {
  .customer-dashboard-container {
    padding: 16px;
  }
  
  .main-content {
    grid-template-columns: 1fr;
  }
}
</style>